package com.itcast.donkey.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itcast.donkey.R;
import com.itcast.donkey.adapters.ScenicAdapter;
import com.itcast.donkey.modles.ScenicSpotModles;
import com.itcast.donkey.modles.UriModles;
import com.yalantis.phoenix.PullToRefreshView;

import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 点击攻略之后进入的景区界面
 * 攻略下的第二层页面
 * AttackFragment-->ScenicSpotActivity
 * Created by lanouhn on 16/8/24.
 */
public class ScenicSpotActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_back, iv_chan, iv_share;
    private TextView tv_title;
    private RecyclerView recyclerView;
    private ScenicAdapter adapter;
    private ArrayList<ScenicSpotModles> spotModlesList;

    private PullToRefreshView pull;

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scenic_spot);

        sp = getSharedPreferences("attackArea", MODE_PRIVATE);
        editor = sp.edit();

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.back_scenic_apot);
        iv_chan = (ImageView) findViewById(R.id.iv_chan_scenic_spot);
        tv_title = (TextView) findViewById(R.id.tv_title_scenic_spot);
        iv_share = (ImageView) findViewById(R.id.iv_share_scenic_spot);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView_scenic_spot);

        pull = (PullToRefreshView) findViewById(R.id.pull_activity_spot);
    }

    private void initData() {
        Intent intent = getIntent();
        //设置标题
        String title = intent.getStringExtra("title");
        tv_title.setText(title);
        //得到从AttackAdapter传过来的ID
        int id = intent.getIntExtra("id", 0);
        editor.putBoolean("isNull", false);
        editor.putInt("id", id);
        editor.putString("areaName", title);
        editor.commit();
        final String uri = UriModles.ATTACK_CLICK_FRONT_SCENIC_SPOT_URL + id + UriModles.ATTACK_CLICK_END_SCENIC_SPOT_URL;
        /**
         * 根据ID合并接口，获取网络图片
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                final Request request = new Request.Builder()
                        .url(uri)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(4);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();
                        spotModlesList = new ArrayList<>();
                        try {
                            JSONArray array = new JSONArray(result);
                            for (int i = 0; i < array.length(); i++) {
                                ScenicSpotModles spotModles = gson.fromJson(array.get(i).toString(), ScenicSpotModles.class);
                                spotModlesList.add(spotModles);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (spotModlesList.size() > 0) {
                            handler.sendEmptyMessage(5);
                        } else {
                            handler.sendEmptyMessage(6);
                        }
                    }
                });
            }
        }).start();
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 4:
                    Toast.makeText(ScenicSpotActivity.this, "获取网络失败", Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    adapter = new ScenicAdapter(ScenicSpotActivity.this, spotModlesList);
                    recyclerView.setAdapter(adapter);

                    LinearLayoutManager linManger = new LinearLayoutManager(ScenicSpotActivity.this);
                    recyclerView.setLayoutManager(linManger);
                    break;
                case 6:
                    Toast.makeText(ScenicSpotActivity.this, "解析失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void initEvent() {
        iv_back.setOnClickListener(this);
        iv_share.setOnClickListener(this);
        iv_chan.setOnClickListener(this);

        pull.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pull.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pull.setRefreshing(false);
                    }
                }, 3000);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_chan_scenic_spot:
            case R.id.back_scenic_apot:
                Intent intent = new Intent(ScenicSpotActivity.this, MainActivity.class);
                intent.putExtra("xia", 1);
                startActivity(intent);
                finish();
                break;
            case R.id.iv_share_scenic_spot:
                showShare();
                break;
        }
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("QQ空间分享测试");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }
}
